//
//  AlbumViewController.m
//  A_program
//
//  Created by dlios on 15-5-23.
//  Copyright (c) 2015年 BayMax. All rights reserved.
//

#import "NovelAlbumViewController.h"
#import "NovelAlbumHeaderModel.h"
#import "NovelAlbumListModel.h"
#import "NovelAlbumTableViewCell.h"
#import "NovelAlbumHeaderView.h"
#import "ConnectModel.h"
#import "NovelAlbumNextViewController.h"
#import "MJRefresh.h"
#import "PlayerViewController.h"
#import <Reachability.h>
#import "NovelModel.h"
#import "NovelDatabase.h"
#import "MyAlbumFirstButton.h"
#import "LoginNextViewController.h"

@interface NovelAlbumViewController ()<UITableViewDataSource,UITableViewDelegate,AlbumTitleDelegate,AlbumFristNextButtonDelegate>

@property (nonatomic, retain) NSMutableArray *playArray;

@end

@implementation NovelAlbumViewController
- (void)dealloc
{
    [_playArray release];
    [self.albumHeaderModel release];
    [self.albumListModel release];
    [self.albumViewArray release];
    [self.albumTableView release];
    [self.publicPath release];
    [self.albumId release];
    [self.headerView release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.albumViewArray = [NSMutableArray array];
        self.playArray = [NSMutableArray array];
        self.publicPath = [NSString string];
        self.albumPageCount = 2;
    }
    return self;
}
- (void)loadView{
    [super loadView];
    [self createAlbumTableView];
    if ([self isConnectionAvailable:0]) {
        [self createAlbumViewData:self.publicPath];
                }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
}
//判断网络使用
-(BOOL) isConnectionAvailable:(NSInteger)count{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"没网");
            if (count == 1) {
                [self.albumTableView.header endRefreshing];
            }else if(count == 2){
                [self.albumTableView.footer endRefreshing];
            }
            
            [self alertView:@"没有网络连接"];
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"用的WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            NSLog(@"3G");
            [self alertView:@"使用3G连接"];
            break;
    }
    
    
    return isExistenceNetwork;
}
// 警告框
- (void)alertView:(NSString *)str
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
    [alert setDelegate:self];
    [alert show];
    [alert release];
    
}

//数据方法
- (void)createAlbumViewData:(NSString *)dataUrl{

    [ConnectModel connectWithUrl:dataUrl block:^(NSData *data) {
        self.albumHeaderModel = [[NovelAlbumHeaderModel alloc]init];
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
        [self.albumHeaderModel setValuesForKeysWithDictionary:myHeaderDic];
        
        NSMutableDictionary *secondDic = [dic objectForKey:@"tracks"];
        self.playArray = [secondDic objectForKey:@"list"];
        for (NSMutableDictionary *mydic in _playArray) {
            self.albumListModel = [[NovelAlbumListModel alloc]init];
            [self.albumListModel setValuesForKeysWithDictionary:mydic];
            [self.albumViewArray addObject:self.albumListModel];
        }
        [self.albumTableView reloadData];

        //HeaderData数据
        
        [self.headerView createHeaderView:self.albumHeaderModel];
        [self.albumHeaderModel release];
        [self.albumListModel release];
    }];
   }
- (void)createAlbumTableView{
    self.albumTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height*0.9)];
    [self.view addSubview:self.albumTableView];
    self.albumTableView.delegate = self;
    self.albumTableView.dataSource = self;
    [self createAlbumTableViewHeader];
    //上拉加载下拉刷新
    [self.albumTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.albumTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.albumTableView release];
   

}

//下拉刷新点击事件
- (void)loadNewData:(id)sender
{
    if ([self isConnectionAvailable:1]) {
        NSUserDefaults *myLoginName = [NSUserDefaults standardUserDefaults];
        NSInteger myAlbumId = self.albumHeaderModel.albumId;
        NSMutableArray *array = (NSMutableArray *)[NovelDatabase selectNameAlbumId:myAlbumId loginName:[myLoginName objectForKey:@"loginName"]];
        if (array.count == 0) {
            [self.albumFristNextButton setTitle:@"收藏" forState:UIControlStateNormal];
            
        }else{
            [self.albumFristNextButton setTitle:@"已收藏" forState:UIControlStateNormal];
            
        }

        [self.albumTableView reloadData];
        [self.albumTableView.header endRefreshing];
        
    }
   
}
//上拉加载点击事件
- (void)loadMoreData{
    if ([self isConnectionAvailable:2]) {
        NSString *urlDate = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/15",self.albumId,self.albumPageCount];
        [ConnectModel connectWithUrl:urlDate block:^(NSData *data) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary *secondDic = [dic objectForKey:@"tracks"];
            NSMutableArray *myListArray = [secondDic objectForKey:@"list"];
            for (NSMutableDictionary *mydic in myListArray) {
                self.albumListModel = [[NovelAlbumListModel alloc]init];
                [self.albumListModel setValuesForKeysWithDictionary:mydic];
                [self.albumViewArray addObject:self.albumListModel];
            }
            [self.albumTableView reloadData];
            
        }];
        
        // 拿到当前的上拉刷新控件，结束刷新状态
        self.albumPageCount += 1;
        [self.albumTableView.footer endRefreshing];

    }
    

}

//建立headerView
- (void)createAlbumTableViewHeader{
    UIView *AlbumView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/4)];
    [AlbumView setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:0.9]];
    self.headerView = [[NovelAlbumHeaderView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds .size.width, [UIScreen mainScreen].bounds.size.height/4 - 10)];
    
    [self.headerView setBackgroundColor:[UIColor whiteColor]];
    [AlbumView addSubview:self.headerView];
    self.headerView.albumChangeDelegate = self;
    
    //收藏按钮协议
    self.headerView.myAlbumFirstButtonDelegate = self;
    //添加headerView给tabview
    [self.albumTableView setTableHeaderView:AlbumView];
    
    [AlbumView release];
    [self.headerView release];
    [self.fristView release];
}

//收藏按钮
#pragma mark- 
#pragma mark 收藏的按钮判别
- (void)createCollectAction:(NSString *)collect{
    NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];

                NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                    self.novelModel = [[NovelModel alloc]init];
                    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                    [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                    //读取userDefault的信息
                    self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                    self.novelModel.playKind = @"novel";
                    self.novelModel.albumIdMin = [collect integerValue];
                    [NovelDatabase insertWithModel:self.novelModel];
                }];
    
}
//建立详情跳转
- (void)albumChangeViewController{
    NovelAlbumNextViewController *albumNext = [[NovelAlbumNextViewController alloc]init];
    albumNext.albumNextModel = self.albumHeaderModel;
    [self.navigationController pushViewController:albumNext animated:YES];
    [albumNext release];
}

//协议部分
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.albumViewArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cella = @"cell";
    NovelAlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cella];
    if (!cell) {
        cell = [[[NovelAlbumTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cella]autorelease];
    }
    self.albumListModel = [[NovelAlbumListModel alloc]init];
    self.albumListModel = [self.albumViewArray objectAtIndex:indexPath.row];
    //判断收藏按钮状态

     self.headerView.albumFristNextButton.albumId = self.albumListModel.albumId;
    NSUserDefaults *myLoginName = [NSUserDefaults standardUserDefaults];
    NSInteger myAlbumId = self.headerView.albumFristNextButton.albumId;
    NSMutableArray *array = (NSMutableArray *)[NovelDatabase selectNameAlbumId:myAlbumId loginName:[myLoginName objectForKey:@"loginName"]];
    if (array.count == 0) {
        [self.headerView.albumFristNextButton setTitle:@"收藏" forState:UIControlStateNormal];
        
    }else{
        [self.headerView.albumFristNextButton setTitle:@"已收藏" forState:UIControlStateNormal];
        
    }

    //传值
    [cell createAlbumView:self.albumListModel];
    
    return cell;
    
}
//设置每个cell大小
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [UIScreen mainScreen].bounds.size.height/6;
}

// tableView 跳转到播放界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayerViewController *play = [[PlayerViewController alloc]init];
    NovelAlbumListModel *model = [_albumViewArray objectAtIndex:indexPath.row];
    play.trackId = model.trackId;
    play.array = _playArray;
    [self presentViewController:play animated:YES completion:nil];
    [play release];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
